package com.ycfmedical.bed.ui;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.base.BaseMenuActivity;
import com.ycfmedical.bed.service.BluetoothChatService;
import com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil;
import com.ycfmedical.bed.utils.RefreshDataUtils;
import com.ycfmedical.bed.utils.ServerControl;
import com.ycfmedical.bed.wifi.WifiEvent;

import java.sql.Date;
import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.router.Router;

/**
 * 连接蓝牙并显示体温参数界面 Created by Administrator on 2017-03-29.
 */

public class TemperatureShowActivity extends BaseMenuActivity
{
    
    private static final String TAG = "BluetoothChat";
    
    private static final boolean D = true;
    
    public static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 1;
    
    public static final int MESSAGE_READ = 2;
    
    public static final int MESSAGE_WRITE = 3;
    
    public static final int MESSAGE_DEVICE_NAME = 4;
    
    public static final int MESSAGE_TOAST = 5;
    
    public static final String DEVICE_NAME = "device_name";
    
    public static final String TOAST = "toast";
    
    private static final int REQUEST_CONNECT_DEVICE = 1;
    
    private static final int REQUEST_ENABLE_BT = 2;
    
    // ????
    private EditText mOutEditText;
    
    @BindView(R.id.temperature_connect)
    Button temperatureConnect;
    
    @BindView(R.id.temperature_back)
    Button temperatureBack;
    
    @BindView(R.id.temperature_list)
    ListView temperatureList;
    
    private String mConnectedDeviceName = null;
    
    private ArrayAdapter<String> mConversationArrayAdapter;
    
    private StringBuffer mOutStringBuffer;
    
    private BluetoothAdapter mBluetoothAdapter = null;
    
    private BluetoothChatService mChatService = null;
    
    String mac;
    
    @Override
    public void initData(Bundle savedInstanceState)
    {
        // 自动连接到设备
        Bundle bundle = this.getIntent().getExtras();
        mac = bundle.getString("TpKey");
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Intent serverIntent = new Intent(this, DeviceListActivity.class);
        Bundle bundle1 = new Bundle();
        bundle1.putString("TpKey", mac);
        serverIntent.putExtras(bundle1);
        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
    }
    
    @Override
    public void onStart()
    {
        // 第一步 自动连接蓝牙
        super.onStart();
        if (!mBluetoothAdapter.isEnabled())
        {
            // 自动开蓝牙
            try
            {
                mBluetoothAdapter.enable();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            while (!mBluetoothAdapter.isEnabled())
            {
                Log.e("blue close", "blue close");
            }
            connectDevice();
            setupChat();
        }
        else
        {
            if (mChatService == null)
                setupChat();
        }
    }
    
    private void delay(int ms)
    {

        try
        {
            Thread.currentThread();
            Thread.sleep(ms);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public synchronized void onResume()
    {
        super.onResume();
        if (mChatService != null)
        {
            
            if (mChatService.getState() == BluetoothChatService.STATE_NONE)
            {
                mChatService.start();
            }
        }
    }
    
    private void connectDevice()
    {
        try
        {
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac);
            mChatService.connect(device);
        }
        catch (Exception e)
        {
            
        }
    }
    
    private void setupChat()
    {
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.temoerature_item);
        temperatureList.setAdapter(mConversationArrayAdapter);

        mChatService = new BluetoothChatService(this, mHandler);
        mOutStringBuffer = new StringBuffer("");
    }
    
    @Override
    public int getLayoutId()
    {
        return R.layout.activity_temperatureshow;
    }
    
    @Override
    public Object newP()
    {
        return null;
    }
    
    public static void launch(Activity activity)
    {
        Router.newIntent(activity).to(TemperatureShowActivity.class).launch();
    }
    
    private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener()
    {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
        {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP)
            {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if (D)
                Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    
    private void ensureDiscoverable()
    {
        if (D)
            Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
        {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }
    
    private void sendMessage(String message)
    {
        
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED)
        {
            Toast.makeText(this, R.string.bluetooth_connected_break, Toast.LENGTH_SHORT).show();
            return;
        }
        if (message.length() > 0)
        {
            
            byte[] send = message.getBytes();
            mChatService.write(send);
            mOutStringBuffer.setLength(0);
            // 设置数据
            mOutEditText.setText(mOutStringBuffer);
        }
    }
    
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MESSAGE_BLUETOOTH_STATE_CHANGE:
                    if (D)
                        Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    switch (msg.arg1)
                    {
                        case BluetoothChatService.STATE_CONNECTED:
                            // mTitle.setText(R.string.title_connected_to);
                            // mTitle.append(mConnectedDeviceName);
                            temperatureConnect.setEnabled(false);
                            temperatureConnect.setText("已连接");
                            mConversationArrayAdapter.clear();
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            // mTitle.setText(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            // mTitle.setText(R.string.title_not_connected);
                            temperatureConnect.setText("重新连接");
                            temperatureConnect.setEnabled(true);
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[])msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;
                case MESSAGE_READ:
                    // 获取信息
                    byte[] readBuf = new byte[4];
                    byte[] temp = new byte[4];
                    temp = (byte[])msg.obj;
                    for (int i = 0; i < 4; i++)
                    {
                        readBuf[i] = temp[i];
                    }
                    String readMessage = bytesToHexString(readBuf);
                    Log.e("getdata =", readMessage);
                    // 体温数据
                    String temperature = gettemperature(readBuf);
                    // 获取当前时间
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); // 设置时间格式
                    Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
                    String str = formatter.format(curDate);
                    // 打印到界面
                    mConversationArrayAdapter.add(mConnectedDeviceName + ": " + str + "——" + temperature + "℃");
                    // 传输数据到页面
                    RefreshDataUtils refreshDataUtils = RefreshDataUtils.getRefreshDataUtils();
                    refreshDataUtils.setData(Constants.BED_TEMPERATURE, temperature);
                    // 发送数据
                    SendMsgAndSaveTemData(temperature, mac);
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                case MESSAGE_TOAST:
                    break;
            }
        }
    };
    
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (D)
            Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode)
        {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK)
                {
                    // Get the device MAC address
                    String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    try
                    {
                        // Get the BLuetoothDevice object
                        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                        // Attempt to connect to the device
                        mChatService.connect(device);
                    }
                    catch (Exception e)
                    {
                        
                    }
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK)
                {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                }
                else
                {
                    // User did not enable Bluetooth or an error occured
                    Log.d(TAG, "BT not enabled");
                    finish();
                }
        }
    }
    
    public static String bytesToHexString(byte[] src)
    {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0)
        {
            return null;
        }
        for (int i = 0; i < src.length; i++)
        {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2)
            {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    
    public String gettemperature(byte[] data)
    {
        String temp = "";
        if ((data[1] ^ data[2]) == data[3])
        {
            float i = (float)(bytetoint(data[1]) * 256 + bytetoint(data[2])) / 10;
            Log.e("one =", "" + bytetoint(data[1]) * 256);
            Log.e("two =", "" + bytetoint(data[2]));
            temp = "" + i;
        }
        return temp;
    }
    
    public int bytetoint(byte b)
    {
        int i = b;
        i = b & 0xff;
        return i;
    }
    
    private void SendMsgAndSaveTemData(String Value, String Mac)
    {
        int temNum = ConvertOrderCheckoutUtil.decimalToDouble(Value);
        String temNumStr = ConvertOrderCheckoutUtil.integerC10T16(temNum);
        for (int i = temNumStr.length(); i < 4; i++)
        {
            temNumStr = "0" + temNumStr;
        }
        // 传递信息到护士站
        String OrderMsg = Constants.fhHeader + "64" + "0025" + temNumStr + "00000000000000000000000000" + Constants.bedId + "00";
        int length = OrderMsg.length();
        WifiEvent wifi = WifiEvent.getInstance();
        wifi.senddata(OrderMsg);
        // 保存数据到服务器
        ServerControl.SaveTmeAndWeight(temNum+"", Mac);
    }
    
    @OnClick({R.id.temperature_connect, R.id.temperature_back})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.temperature_connect:
                Intent serverIntent = new Intent(TemperatureShowActivity.this, DeviceListActivity.class);
                Bundle bundle1=new Bundle();
                bundle1.putString("TpKey", mac);
                serverIntent.putExtras(bundle1);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                break;
            case R.id.temperature_back:
                finish();
                break;
        }
    }
}
